package com.haoran.dwz.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * 去掉此類后就變成http
 */
@Configuration
@Profile({"h2","dev"})
public class HttpsConfig {
	/**
	 * 启动端口默认是8080;
	 */
	@Value("${server.startport:8080}")
	private int startport;

	/**
	 * ssl端口默认是8443;
	 */
	@Value("${server.port:8443}")
	private int redirectPort;
	
	@Value("${server.ssl.enabled:false}")
	private boolean enabled;
	
	/**
	 * 采用内置tomcat时这么配置
	 * @return
	 */
	@Bean
	public EmbeddedServletContainerFactory servletContainer() {

		TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
			@Override
			protected void postProcessContext(Context context) {
				if(enabled) {
					SecurityConstraint securityConstraint = new SecurityConstraint();
					securityConstraint.setUserConstraint("CONFIDENTIAL");
					SecurityCollection collection = new SecurityCollection();
					collection.addPattern("/*");
					securityConstraint.addCollection(collection);
					context.addConstraint(securityConstraint);
				}
			}
		};
		tomcat.addAdditionalTomcatConnectors(httpConnector());
		return tomcat;
	}

	private Connector httpConnector() {
		Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
		connector.setScheme("http");
		connector.setPort(startport);
		connector.setSecure(false);
		connector.setRedirectPort(redirectPort);
		return connector;
	}

}
